package com.apes.hr.cultivate.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.DateUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 培训计划
 * @author Linwz
 * @create 2019-06-18 10:11
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = CultivatePlanItem.CONST_TABLE_NAME)
public class CultivatePlanItem extends Model {
    public static final String CONST_TABLE_NAME = "hr_cultivate_plan_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "培训计划明细")
    @Comment("培训计划明细编码")
    private String id;   //培训计划明细编码

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "cultivate_plan_id", referencedColumnName = "ID")
    @Comment("培训计划")
    private CultivatePlan cultivatePlan; //培训计划

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "course_id", referencedColumnName = "ID")
    @Comment("课程")
    private Course course;//课程

//    @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.LAZY)
//    @JoinTable(name = "hr_cultivate_plan_item_courses",
//            joinColumns = {@JoinColumn(name = "course_id", referencedColumnName = "id")},
//            inverseJoinColumns = {@JoinColumn(name = "cultivate_plan_item_id", referencedColumnName = "id")}
//    )
//    private List<Course> courses = new ArrayList<>();
//
//    // 定义培训计划的课程前端界面转化
//    @Transient
//    private List<JSONObject> courseList;

    @Column(name="out_cultivate_plan_uid",length = 4000)
    @Comment("排期方式")
    private String outCultivatePlanUid;  //外部培训人

    @Column(name = "cultivate_plan_place")
    @Comment("培训地点")
    private String cultivatePlanPlace; //培训地点

    @Column(name = "cultivate_plan_list", length = 4000)
    @Comment("内部培训人")
    private String cultivatePlanList;  //内部培训人

    public void setCultivatePlanLists(String cultivatePlanList) {
    }

    @Transient
    private Set<Employee> cultivatePlanSet;

    public Set<Employee> getcultivatePlanSet() {
        if (isWrite() || isLoad()) {
            cultivatePlanSet = getEmployee(this.cultivatePlanList);
        }
        return cultivatePlanSet;
    }
    public void setcultivatePlanSet( Set<Employee> cultivatePlanSet) {
        this.cultivatePlanSet = cultivatePlanSet;
        if (!isWrite()) {
            this.cultivatePlanList = toConvertEmployee(this.cultivatePlanSet);
        }
    }

    @Transient
    private Set<Employee> getEmployee(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<Employee> persons = new HashSet<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(EmployeeRepository.class).findOne(StringUtils.split(person, "|")[0]));
            }
        }
        return persons;
    }

    private String toConvertEmployee(Set<Employee> persons) {
        StringBuffer sb = new StringBuffer();
        for (Employee employee : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(employee.getId());
            sb.append("|");
            sb.append(employee.getName());  // 格式 id|description;
        }
        return sb.toString();
    }

    public void setSchedulings(String schedulings) {
    }

    @Transient
    private Set<Enumeration> schedulingsSet;

    public Set<Enumeration> getSchedulingsSet() {
        if (isWrite() || isLoad()) {
            schedulingsSet = getReason(this.schedulings);
        }
        return schedulingsSet;
    }
    public void setSchedulingsSet(Set<Enumeration> schedulingsSet) {
        this.schedulingsSet = schedulingsSet;
        if (!isWrite()) {
            this.schedulings = toConvertReason(this.schedulingsSet);
        }
    }
    @Transient
    private Set<Enumeration> getReason(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<Enumeration> persons = new HashSet<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(EnumerationRepository.class).findOne(StringUtils.split(person, "|")[0]));
            }
        }
        return persons;
    }

    private String toConvertReason(Set<Enumeration> persons) {
        StringBuffer sb = new StringBuffer();
        for (Enumeration enumeration : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(enumeration.getId());
            sb.append("|");
            sb.append(enumeration.getDescription());  // 格式 id|description;
        }
        return sb.toString();
    }


    @Column(name="schedulings",length = 4000)
    @Comment("排期方式")
    private String schedulings;  //排期方式

    @OneToMany(mappedBy="cultivatePlanItem",cascade=CascadeType.ALL)
    @Comment("开课时间段")
    private Set<CultivatePlanTime> cultivatePlanTimes = new HashSet<>();//开课时间段
    public Set<CultivatePlanTime> getcultivatePlanTimes() {
        if (cultivatePlanTimes == null) return null;
        for (CultivatePlanTime time: cultivatePlanTimes) {
            time.setCultivatePlanItem(this);
        }
        return cultivatePlanTimes;
    }
    public void setcultivatePlanTimes(Set<CultivatePlanTime> cultivatePlanTimes) {
        if (cultivatePlanTimes == null) cultivatePlanTimes = new HashSet<>();
        this.cultivatePlanTimes.clear();
        this.cultivatePlanTimes.addAll(cultivatePlanTimes);
    }

    @Column(name = "repeal", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("是否已终止")
    private boolean repeal = false; //是否已终止

}
